/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers.classes;

import classes.Breadcrumbs;
import classes.HibernateUtil;
import dao.PrivateMessageDao;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import models.PrivateMessage;
import models.User;

/**
 * This Controller shows the full list of private messages of the Inbox, Outbox
 * and Trash.
 *
 * @author Sander
 */
public class PrivateMessageController extends HttpServlet {

    /**
     * This doGet checks which folder needs to be called and shows all the
     * private messages within it.
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String[] folders = {"inbox", "outbox", "trash"};
        String folder = request.getParameter("folder");

        if (!Arrays.asList(folders).contains(folder)) {
            folder = "inbox";
        }

        String str_folder = folder.substring(0, 1).toUpperCase() + folder.substring(1);

        HibernateUtil hu = new HibernateUtil();
        PrivateMessageDao dao = new PrivateMessageDao(hu.openSession());

        User user = (User) request.getSession().getAttribute("user");

        request.setAttribute("folder", folder);
        request.setAttribute("str_folder", str_folder);

        // Breadcrumbs
        Breadcrumbs[] breadcrumbs = {
            new Breadcrumbs("Index", "Home"),
            new Breadcrumbs("PrivateMessage", str_folder)
        };
        request.setAttribute("breadcrumbs", breadcrumbs);

        // If the user clicks on empty trash
        if (folder.equals("trash") && request.getParameter("empty") != null) {
            // Removes all private messages in trash
            dao.removeAllPrivateMessages(user.getMember_id());
            RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/private_messages.jsp");
            dispatcher.forward(request, response);
            return;
        }

        List<PrivateMessage> private_messages = dao.findAllByFolder(folder, user.getMember_id());

        request.setAttribute("private_messages", private_messages);

        hu.close();

        RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/private_messages.jsp");
        dispatcher.forward(request, response);
    }
}
